﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public  class UdpMulticastReceiver
{
    private const string MulticastAddress = "224.100.0.1";
    private const int MulticastPort = 11000;
    private const int BufferSize = 65507; // UDP最大数据报大小


    public static async Task Start()
    {
        using (UdpClient udpClient = new UdpClient())
        {
            try
            {
                // 绑定到本地端口
                udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, MulticastPort));

                // 加入组播组
                udpClient.JoinMulticastGroup(IPAddress.Parse(MulticastAddress));

                Console.WriteLine("加入组播组，开始接收数据...");

                // 异步接收数据
                while (true)
                {
                    UdpReceiveResult result = await udpClient.ReceiveAsync();
                    byte[] receivedBytes = result.Buffer;
                    IPEndPoint remoteEndPoint = result.RemoteEndPoint;

                    // 使用Task.Run将数据处理放到线程池中执行
                    _ = Task.Run(() => ProcessData(receivedBytes, remoteEndPoint));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生异常: {ex.Message}");
            }
            finally
            {
                // 离开组播组
                udpClient.DropMulticastGroup(IPAddress.Parse(MulticastAddress));
            }
        }
    }

    private static void ProcessData(byte[] data, IPEndPoint remoteEndPoint)
    {
        try
        {
            // 模拟数据处理（例如解析、存储等）
            string receivedData = Encoding.UTF8.GetString(data);
            Console.WriteLine($"从 {remoteEndPoint.Address}:{remoteEndPoint.Port} 接收到数据: {receivedData}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"数据处理异常: {ex.Message}");
        }
    }
}